package com.crazymakercircle.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;

@Slf4j
public class FileHelper {
    private String filepath;

    public FileHelper(String filepath) {
        this.filepath = filepath;
    }

    public String getTestDataString() throws Exception {

        String src = filepath;
        log.info("filepath 1=" + filepath);
        if (!new File(filepath).exists()) {
            filepath = System.getProperty("user.dir") + File.separator + src;
            log.info("user.dir  filepath =" + filepath);
            log.info("filepath 2=" + filepath);

        }
        if (!new File(filepath).exists()) {
            URL classPath = this.getClass().getClassLoader().getResource("");
            filepath = classPath.getPath() + File.separator + src;
            log.info("getClassLoader filepath =" + filepath);
        }
//"/work/tester-master-1.0-SNAPSHOT/bin/demo.json"
        log.info("filepath 3=" + filepath);
        FileInputStream fis = new FileInputStream(this.filepath);
        InputStreamReader isr = new InputStreamReader(fis, "utf-8");
        BufferedReader br = new BufferedReader(isr);

        StringBuilder testdatastring = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            testdatastring.append(line);
        }
        fis.close();
        return testdatastring.toString();
    }

    public JSONObject getjsondata(String datastr) {
        JSONObject jsondata = JSON.parseObject(datastr);
        return jsondata;
    }

}
